package yxy.game.pm2.module.union;

import java.util.Collection;

import org.joda.time.DateTime;
import org.redisson.api.RList;

import yxy.game.pm2.bean.module.BaseGameRedisLockBean;

public class UnionLog extends BaseGameRedisLockBean {

	// bean===========================================================================

	private DateTime time;
	private String text;

	public DateTime getTime() {
		return time;
	}

	public void setTime(DateTime time) {
		this.time = time;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	// redis==========================================================================

	static private String key(String unionCode) {
		return String.format("UNION:%s:LOG", unionCode);
	}

	static private RList<UnionLog> touch(String unionCode) {
		return redis().client().getList(key(unionCode));
	}

	static public void add(String unionCode, String text) {
		String lockKey = lockKey(unionCode);
		try {
			if (tryLock(lockKey)) {
				RList<UnionLog> list = touch(unionCode);
				{
					UnionLog unionLog = new UnionLog();
					unionLog.setTime(DateTime.now());
					unionLog.setText(text);
					list.add(unionLog);
				}
				if (list.size() > limitSize() && limitSize() > 0) {
					list.remove(0);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			unlock(lockKey);
		}
	}

	static private int limitSize() {
		return 100;
	}

	static public Collection<UnionLog> all(String unionCode) {
		return touch(unionCode).readAll();
	}

	static private String lockKey(String unionCode) {
		return String.format("lock:%s", key(unionCode));
	}

}
